<?php
class p_episode extends Model{
	public static function getTableName(){
		return 'p_episode';
	}

	public function set($object){
		$this->programme_id = !isset($object->programme_id) ? '0' : $object->programme_id;
		$this->onair_episode_no = !isset($object->onair_episode_no) ? '0' : trim($object->onair_episode_no);
		$this->original_episode_no = !isset($object->original_episode_no) ? '0' : trim($object->original_episode_no);
		$this->average_rating = !isset($object->average_rating) ? '0' : trim($object->average_rating);
		$this->first_time_onair = !isset($object->first_time_onair) ? '' : $object->first_time_onair;
		$this->publish_datetime = !isset($object->publish_datetime) ? '' : $object->publish_datetime;
		$this->expire_datetime = !isset($object->expire_datetime) ? '' : $object->expire_datetime;
		$this->other_language_episodes = !isset($object->other_language_episodes) ? '' : trim($object->other_language_episodes);
		$this->highlighted_cast_roles = !isset($object->highlighted_cast_roles) ? '' : $object->highlighted_cast_roles;
		$this->casts = !isset($object->casts) ? '' : $object->casts;
		$this->available_tag_types = !isset($object->available_tag_types) ? '' : $object->available_tag_types;
		$this->tags = !isset($object->tags) ? '' : $object->tags;
		$this->folders = !isset($object->folders) ? '' : $object->folders;
		$this->status = !isset($object->status) ? '0' : $object->status;
		$this->created_at = !isset($object->created_at) ? '' : $object->created_at;
		$this->created_by = !isset($object->created_by) ? '' : $object->created_by;
		$this->modified_at = !isset($object->modified_at) ? '' : $object->modified_at;
		$this->modified_by = !isset($object->modified_by) ? '' : $object->modified_by;
	}

	public function getDetails($episode_id)
	{
        $sql = "
            select 
                a.* , 
                b.* 
            from
                ".self::getTableName()." a 
            left join 
                `p_episode-language` b on a.id=b.episode_id 
            where 
                episode_id='{$episode_id}' group by episode_id";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);

        $sql = "SELECT * FROM `p_episode-language` WHERE `episode_id` = " . $episode_id;
        $ro = Model::$dbo['r']->findBySql(__class__, $sql);
        foreach ($ro as $obj) {
            $episode_language[$obj->language_id] = $obj;
        }
		
        $num_language_en = language::getLanguageId(AC::LANGUAGE_EN);
        if (!isset($episode_language[$num_language_en])) {
            $episode_language[$num_language_en]->title = '';
            $episode_language[$num_language_en]->description = ''; 
            $episode_language[$num_language_en]->description_short = '';
        }
        $ret[0]->episode_language = $episode_language;
		return $ret[0];
	}

	public function getEpisode($episode_id)
	{
        $sql = "
            select 
                a.* 
            from
                ".self::getTableName()." a 
            where 
                id='{$episode_id}' group by id";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);
       	return $ret[0];
	}

	public static function getEpisodeID($programme_id, $onair_episode_no)
	{
	    $sql = "select id from ".self::getTableName()." where onair_episode_no='{$onair_episode_no}' and programme_id='{$programme_id}'";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);
		return isset($ret[0]) ? $ret[0]->id : '';
    }

    public static  function getEpisodeNumByProgrammeId($pid)
    {
        $sql = 'select onair_episode_no from p_episode where `status`!='. AC::STATUS_DELETED .' AND programme_id = :pid';
        $params = array(':pid'=>$pid);
        $result = Model::selectBySql($sql,$params);
        $epis  = array();
        if(!empty($result))
        {
            foreach($result as $epi)
            {
                $epis[] = $epi['onair_episode_no'];
            }
        }
        $ret  = implode(',',$epis);
        return $ret;
    }


	public function getList()
	{
		$sql = "select * from ".self::getTableName()." a left join `p_episode-language` b on a.id=b.episode_id";
		return Model::$dbo['r']->findBySql(__class__, $sql);
	}

	public function getResultList($findRelation, $field, $operation, $value, $start, $length, $sidx	= NULL, $sord = NULL, $unpublish = 0)
	{
		$find	=	$findRelation['mapField'];
		$db_con = ($unpublish == 1) ? CommonUtils::getDbConn(0,'preview') : Model::$dbo['r'];
        # first, deal with title party!
        $titleWhere =   $programmeTitleIds  =   NULL;
        $pathWhere  =   NULL;
        $searchSing =   FALSE;
        $programmes =   array();
        $resField   =   $resOperation   =   $resValue   =   array();

        foreach ($field as  $fieldKey   =>  $fieldValue) {
            switch ($fieldValue) {
            case 'title':
                $titleWhere[]   =   Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                break;
            case 'path':
                $pathWhere[]    =   Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                break;
            case 'premium':
                if ($value[$fieldKey] != '2') { // 2=all
                    $resField[$fieldKey] = $fieldValue;
                    $resOperation[$fieldKey] = $operation[$fieldKey];
                    $resValue[$fieldKey] = $value[$fieldKey];
                }
                break;
            case 'premium_items':
                if (isset($value[$fieldKey]) && is_array($value[$fieldKey])) {
                    foreach ($value[$fieldKey] as $_value) {
                        if ($_value == 'subscription_flag') {
                            $where_extra[] = '`subscription_flag`=1';
                        } else if ($_value == 'ppv_flag') {
                            $where_extra[] = '`ppv_flag`=1';
                        }
                    }
                }
                break;
            case 'video_type':
                if ($value[$fieldKey] != 'all') { // 2=all
                    $resField[$fieldKey] = $fieldValue;
                    $resOperation[$fieldKey] = $operation[$fieldKey];
                    $resValue[$fieldKey] = $value[$fieldKey];
                }
                break;
            default:
                $resField[$fieldKey]    =   $fieldValue;
                $resOperation[$fieldKey]=   $operation[$fieldKey];
                $resValue[$fieldKey]    =   $value[$fieldKey];
                break;
            }
        }

        if (!empty($titleWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByTitle($titleWhere,$field,$operation);
        }
        if (!empty($pathWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByPath($pathWhere);
        }

        if ($searchSing)
        {
			if (count($programmes)>1){
				$programmes = call_user_func_array('array_intersect',$programmes);
			}else{
				$programmes = $programmes[0];
			}
			$programmeTitleIds = implode(',', $programmes);   

            if (empty($programmeTitleIds))  $programmeTitleIds  =   '""';
            $programmeTitleIds  =   ' WHERE `p_programme-language`.programme_id IN ('. $programmeTitleIds. ')';
        }
		$where	=	Model::assembleWhereSentence($find, $resField, $resOperation, $resValue);
		if (!empty($where))
		{
			$where	=	' WHERE '. $where;
        } else {
            $where = ' WHERE 1';
        }

        if (!empty($where_extra)) {
            $where .= ' AND ' . implode(' AND ', $where_extra);
        }

		$subSql	=	'
				SELECT DISTINCT
					`p_episode`.id					        AS	id,
                    `p_episode`.programme_id                AS  programme_id,
					GROUP_CONCAT(`p_programme-language`.title SEPARATOR "\n\t")	AS	title,
					`p_episode`.onair_episode_no		    AS	onair_episode_no,
					`p_episode`.first_time_onair	        AS	premier_time_onair,
                    `p_episode`.status                      AS  record_status,
					`p_episode`.modified_at			        AS	modified_at,
					`p_episode`.modified_by			        AS	modified_by,
                    `p_programme`.premium_flag AS premium,
                    `p_programme`.video_type AS video_type,
                    `p_programme_premium`.ppv_flag,
                    `p_programme_premium`.subscription_flag
                FROM p_episode 
                LEFT JOIN `p_programme` ON (`p_episode`.programme_id = `p_programme`.id)
                LEFT JOIN `p_programme_premium` ON (`p_episode`.programme_id = `p_programme_premium`.programme_id)
                INNER JOIN `p_programme-language`	ON (`p_episode`.programme_id = `p_programme-language`.programme_id)
                '. $programmeTitleIds. '
				GROUP BY id
				';

		$sql=	'
			SELECT
				id,
                programme_id,
				title,
				onair_episode_no,
                record_status,
				premier_time_onair,
				modified_at,
				modified_by
			FROM
			(
				'. $subSql. '
			)	AS	findApi
			'.	$where;

		# Order By ...
		$orderBy=	$orderTmp   =   NULL;
		if (!empty($sidx)	&&	!empty($find[$sidx]))
		{
			$orderTmp	=	$find[$sidx];
			if ('desc'	==	$sord)
			{
				$orderTmp	.=	' DESC ';
			}
			elseif ('asc'	==	$sord)
			{
				$orderTmp	.=	' ASC ';
            }
            $orderBy[]  =   $orderTmp;
		}

        if (!empty($where))
        {
            foreach ($field as  $value)
            {
                if (empty($find[$value]))   continue;
                if ('path'  ==  $value)     continue;
                $orderBy[]  =   $find[$value];
            }
        }

        if (empty($orderBy))    $orderBy[]  =   '`findApi`.`modified_at` DESC';

        $orderBy    =   ' ORDER BY '. implode(', ', $orderBy);
		$dataSql	=	$sql. $orderBy. ' LIMIT '. $start. ', '. $length;
		$totalSql	=	'SELECT count(*) AS num FROM ('. $sql. ')	AS	tmp';

		$result	=	$db_con->findBySql(__class__,$dataSql);
		$retAll	=	$db_con->findBySql(__class__,$totalSql);

        if (empty($retAll[0]->num)) $retAll[0]->num =   0;
        if (empty($result[0]))      $result         =   array();
		$list	=	array();
		$list['page']	=	ceil($start / $length) + 1;
		$list['total']	=	ceil($retAll[0]->num / $length);
		$list['records']=	$retAll[0]->num;

		foreach	($result	as	$gridData)
		{
			$tmp			=	array();
			$tmp['id']		=	$gridData->id;
			$tmp['cell']	=	array();

			$gridData->title    = explode("\n\t",$gridData->title);
			$gridData->title[0] = htmlentities($gridData->title[0],ENT_QUOTES,'UTF-8');
			$gridData->title[1] = isset($gridData->title[1]) ? htmlentities($gridData->title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->title    = implode('<br />',$gridData->title);

			$gridData->modified_at= str_replace(' ','<br />',$gridData->modified_at);
			$gridData->premier_time_onair = str_replace(' ','<br />',$gridData->premier_time_onair);

            $originalStatus =   $gridData->record_status;
            if (!empty($unpublish))
            {
                //$publish    =   Model::object2array(publish_log::getPublishLog(__class__, $gridData->id));
                $_publish = publish_log::getPublishLog(__class__, $gridData->id);
                $publish    = count((array)$_publish) <= 0 ? array() :  Model::object2array($_publish);
                $publish = isset($publish['premium']) ? $publish['premium'] : array();
                $gridData->record_status    =   NULL;
                $gridData->modified_by      =   NULL;
                $gridData->modified_at      =   NULL;
                if (isset($publish['action'])   &&  isset(AC::$publicLogAction[$publish['action']]))
                {
                    $gridData->record_status    =   AC::$publicLogAction[$publish['action']];
                    isset($publish['published_by']) &&  $gridData->modified_by  =   $publish['published_by'];
                    isset($publish['published_at']) &&  $gridData->modified_at  =   $publish['published_at'];
                }
            }
            else
            {
                isset(AC::$op_status[$gridData->record_status]) &&  $gridData->record_status    =   AC::$op_status[$gridData->record_status];
            }

			foreach ($find	as	$name	=>	$column) {
                switch ($name) {
                case 'programme_id':
                case 'path':
                case 'premium':
                case 'premium_items':
                case 'video_type':
                    break;
                default:
                    $tmp['cell'][] = $gridData->$name;
                    break;
                }
			}

            $delEdit    =   $delView    =   NULL;
            if (AC::STATUS_DELETED !=   $originalStatus &&  empty($unpublish))
            {
                $delEdit    =	'<a title="Edit" href="get_episode.html?act=edit&step=2&id='. $gridData->id. '" class="btn edit ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"/>Edit</a>';
            }
            if (empty($unpublish)   ||  (isset($publish['action'])  &&  AC::LOG_OP_PREMIUM_PUBLISH  ==  $publish['action']))
            {
                $delView    =   '<a title="View" href="get_p_episode.html?act=view&step=2&id='. $gridData->id. '&unpublish='. $unpublish. '" class="btn view ui-state-default ui-corner-all"><span class="ui-icon ui-icon-image"/>View</a>';
            }
            $tmp['cell'][]  =   $delEdit. $delView;
			$list['rows'][]	=	$tmp;
            unset($publish);
		}
		return	$list;
	}

    /**
     * get proofread SQL
     * @param   $id Int
     * @return  Array
     */
    public function getProofread($id)
    {
        if (empty($id)) return  array();
        $sqlArr =   array(
                    'episode'           =>  array('id = "'. $id. '"'),
                    'episode-language'  =>  array('episode_id = "'. $id. '"'),
                    'episode-video'     =>  array('episode_id = "'. $id. '"'),
                );

        $sqlArray   =   array();
        foreach ($sqlArr    as  $tableName  =>  $whereArray)
        {
            $sqlArray[$tableName]   =   Model::assembleGetProofreadSql($tableName, $whereArray);
        }
        return  $sqlArray;
    }

}
?>
